﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using OA.Manager;
using OA.Model;
using OA.Utility;

namespace OA.Bll.Personnel
{
    public class DeptEmployeePresenter : BasePresenter<DeptInfo>
    {
        private ManagerParent<DeptInfo> _manager = new ManagerParent<DeptInfo>();
        private ManagerParent<EmployeeInfo> _managerParent=new ManagerParent<EmployeeInfo>(); 

        public  string GetDeptTreJson()
        {
            List<DeptInfo> deptInfos = _manager.GetSearchAll("");
            List<EmployeeInfo> employeeInfos = _managerParent.GetSearchAll("");
            return GetTreeJson(employeeInfos, deptInfos);
        }

        public string GetTreeJson(List<EmployeeInfo> employees , List<DeptInfo>deptInfos )
        {
            StringBuilder builder = new StringBuilder();
            if (deptInfos != null && deptInfos.Count > 0)
            {
                builder.Append("[");
                foreach (var deptInfo in deptInfos)
                {

                    builder.Append("{\"id\":" + deptInfo.Id + ",\"text\":\"" + deptInfo.DeptName + "\"");
                    builder.Append(GetTreeChild(employees, deptInfo.Id.ToString(CultureInfo.InvariantCulture)));
                    builder.Append("},");

                }
                builder.Remove(builder.Length - 1, 1);
                builder.Append("]");
            }
            return builder.ToString();
        }


        public string GetTreeChild(List<EmployeeInfo> employees, string pid)
        {
            StringBuilder builder = new StringBuilder();
            List<EmployeeInfo> employeeInfos = employees.Where(p => p.DeptId.ToString() == pid).ToList();
            if (employeeInfos.Count > 0)
            {
                builder.Append(",\"children\":[");
                foreach (var employee in employeeInfos)
                {
                    builder.Append("{ \"id\":" + employee .Id.ToString(CultureInfo.InvariantCulture)+ ",\"text\":\"" +employee.EmployeeName+ "\"");
                    //GetTreeChild(dt, dr["bmid"].ToString());
                    builder.Append(",\"attributes\":{ }},");
                }
                builder.Remove(builder.Length - 1, 1);
                builder.Append("]");
            }
            return builder.ToString();
        }
    }
}
